from datetime import timedelta
import datetime
import random
import string
import pickle
import re
from google.appengine.api import mail
from models.model import *
from updateInfo import maxTitleLength, maxWordsPerArenaEntity
from Transactions import getStockRef


def openComp(amount,emailList, current_user, startdate, enddate,title, publiccomp, keywordsList, comptype, owner, advFlag):
        """ Insert new competition to database """
        # pre condition: valid startdate & enddate
        competition=Competition()
        
        if len(title)==0 or len(title)>maxTitleLength:
            return -3,-1
        
        # Arena is advertisment
        if advFlag:
            # Check if owner has enough money to open this competition
            if current_user.realMoney<amount:
                return -1,-1
            competition.compamount=0
            competition.advamount=amount
            competition.isAd=True
                        
        else:
            # Check if owner has enough money to open this competition
            if current_user.bankamount<amount:
                return -1,-1
            competition.compamount=amount
            competition.advamount=0
            
        competition.password="".join([random.choice(string.letters+string.digits) for x in range(8)])
        todayDate=datetime.date.today()
        competition.startdate=todayDate+timedelta(days=startdate)
        competition.owner = owner
        competition.enddate=competition.startdate+timedelta(days=enddate)
        competition.title=title
        competition.type=comptype
        if publiccomp:
            competition.public=True
        else:
            competition.public=False
        
        compKeywords=[]
        emailTitle=""
        # If Arena type
        if comptype==1:

            emailTitle="an Arena Competition"
            for keywords in keywordsList:
                i=0
                currList=[]
                keywords=keywords.split(",")
                for keyword in keywords:
                    # Max of maxWordsPerArenaEntity words per option
                    if i==maxWordsPerArenaEntity:
                        break;
                    stockToAdd=getStockRef(keyword)
                    if stockToAdd==-1:
                        return -2,-1
                    currList.append(stockToAdd.key())
                    # Increase arena reference counter
                    stockToAdd.arenacounter+=1
                    stockToAdd.put()
                    i+=1
                compKeywords.append(currList)
                competition.compKeywordsAmount.append(1.0)
            competition.arenaKeywords=pickle.dumps(compKeywords)
        
        # If portfolio type
        elif comptype==0:
            emailTitle="a Portfolio Competition"
            
        competition.put()
        compURL="http://mytrendse3.appspot.com/Competition?id=%s&PKey=%s" % (str(competition.key()),competition.password)
        # Send Email Invitations
        for email in emailList:
            if re.match("^.+\\@gmail.com", email):
                #query=TrendUsers.gql("WHERE tuser = :1" , users.User(email))
                #query=query.fetch(1)
                #if len(query)>0:
                    # Send email message
                mail.send_mail(sender="TrendSE <trendse.team@gmail.com>",
                                    to="<" + email + ">",
                                    subject="Invitation to %s on TrendSE" % (emailTitle),
                                    body="Hi!\n\nYou have been invited by %s to compete in TrendSE!\n\nCompetition Title:\"%s\"\nTo join this competition please click on the following link:\n%s\n\nGood Luck!\nTrendSE Team" % (current_user.tuser.nickname().capitalize(), title, compURL))
        return competition, competition.password
        
def joinCompetition(current_user,competition, compType, selection):
            """ Join current_user to competition """

            # User doesnt have enough money to join and status is not 0 (meaning user is trying to join after competition started)
            if current_user.bankamount<competition.compamount or competition.status<>0:
                return -1
            else:
                competition.members.append(current_user.key())
                # In case of portfolio competition
                if compType==0:
                    competition.membersAmount.append(1.0)
                # In case of portfolio competition
                elif compType==1:
                    try:
                        selection=int(selection)
                    except:
                        # selection is not int
                        return -2
                    # selection not in range (1-4)
                    if selection<0 or selection>4:
                        return -2
                    else:
                        competition.membersChoice.append(selection)
                # Wrong type of competition
                else:
                    return -2
                        
                current_user.complist.append(competition.key())
                current_user.bankamount=current_user.bankamount-competition.compamount
                current_user.totalamount=current_user.totalamount-competition.compamount
                competition.put()
                current_user.put()
            return 1
        
def openAdArena(current_user,compamount):
    """ Deduct advertiser amount from real money account """
    if current_user.realMoney<compamount:
        return 0
    current_user.realMoney=current_user.realMoney-compamount
    current_user.put()
    return 1


def sortIndex(list):
    """ sorts list of integers into list of lists of their index position """
    sortedIndexList=[]
    sortedList=[]
    keyWordIndex=0
    i=0
    for amount in list:
        # Enter the first amount as list element index to the first place in sortedIndexList 
        if len(sortedIndexList)==0:
            sortedIndexList.append([keyWordIndex])
            sortedList.append([amount])
            keyWordIndex=keyWordIndex+1
            i=i+1
            continue
        currIndex=0
        end=len(sortedList)
        for listElem in sortedList:
            if currIndex < end:
                if amount > listElem[0]:
                    sortedIndexList.insert(currIndex,[keyWordIndex])
                    sortedList.insert(currIndex,[amount])
                    keyWordIndex=keyWordIndex+1
                    break
                elif amount == listElem[0]:
                    sortedIndexList[currIndex].append(keyWordIndex)
                    sortedList[currIndex].append(amount)
                    keyWordIndex=keyWordIndex+1
                    break
                else:
                    if currIndex==(end-1):
                        sortedIndexList.insert(currIndex+1,[keyWordIndex])
                        sortedList.insert(currIndex+1,[amount])
                        keyWordIndex=keyWordIndex+1
                        break
                    else:
                        currIndex=currIndex+1
            else:
                print "error"
                break
    return sortedIndexList

def sortWinners(sortedIndexList,members,membersChoice):
    """ Sort list of winners """
    winnersSortedList=[]
    for i in range (0,len(sortedIndexList)):
        winnersSortedList.append([])
    
    memberPosition=0
    for member in members:
        listPosition=0
        for list in sortedIndexList:
            if membersChoice[memberPosition] in list:
                winnersSortedList[listPosition].append(member) 
                memberPosition=memberPosition+1
                break
            else:
                listPosition=listPosition+1      
    for list in winnersSortedList:
        if len(list)>0:
            return list